/*
 * AddWordDialog.java
 *
 * Created on Nedeľa, 2008, január 6, 22:32
 */
package eu.easyedu.dictionary.gui;

import eu.easyedu.dictionary.api.model.Dictionary;
import eu.easyedu.dictionary.api.model.Language;
import eu.easyedu.dictionary.api.model.Relationship;
import eu.easyedu.dictionary.api.model.Word;
import eu.easyedu.dictionary.api.model.WordRelationship;
import eu.easyedu.dictionary.api.model.WordType;
import eu.easyedu.dictionary.api.nservice.spi.WordBookService;
import eu.easyedu.dictionary.gui.resources.Bundle;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;
import javax.swing.DefaultCellEditor;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableModel;
import org.openide.util.Lookup;

/**
 *
 * @author  hlavki
 */
public class AddWordDialog extends javax.swing.JDialog {

    private static final long serialVersionUID = 1L;
    private static final Logger log = Logger.getLogger(AddWordDialog.class.getName());
    private Word word;
    private List<WordRelationship> relationships;
    private Dictionary dictionary;
    private boolean wordExists;
    private ColorTextCellRenderer wordTextCellRenderer;
    private WordBookService wbService;

    public static String[] RESULT_TABLE_COLUMN_NAMES = new String[]{
        Bundle.getMessage("AddWordDialog.table.word"),
        Bundle.getMessage("AddWordDialog.table.relationship"),
        Bundle.getMessage("AddWordDialog.table.language")
    };

    /** Creates new form AddWordDialog */
    public AddWordDialog(java.awt.Frame parent, boolean modal, Word word, Dictionary dictionary, boolean wordExists) {
        super(parent, modal);
        initComponents();
        this.wordExists = wordExists;
        if (wordExists) {
            setWordReadOnly();
        }
        this.word = word;
        this.dictionary = dictionary;
        wbService = Lookup.getDefault().lookup(WordBookService.class);
        this.relationships = new ArrayList<WordRelationship>();
        wordTextField.setText(word.getWord());
        setLanguageComboBox();
        setTypeComboBox();
        setRelationTableCellEditors();
    }

    private final void setLanguageComboBox() {
        languageComboBox.setModel(new DefaultComboBoxModel(
                wbService.getAllLanguages(dictionary).toArray()));
        languageComboBox.setSelectedItem(word.getLanguage());
    }

    private final void setTypeComboBox() {
        typeComboBox.setModel(new DefaultComboBoxModel(WordType.values()));
        WordType type = word.getType() != null ? word.getType() : WordType.UNKNOWN;
        typeComboBox.setSelectedItem(type);
    }

    private TableModel getRelationTableModel() {
        TableModel model = new DefaultTableModel(RESULT_TABLE_COLUMN_NAMES, 0);
        return model;
    }

    private void setRelationTableCellEditors() {
        wordTextCellRenderer = new ColorTextCellRenderer(0);
        TableColumn relationColumn = relationTable.getColumnModel().getColumn(1);
        JComboBox relationComboBox = new JComboBox(Relationship.values());
        relationColumn.setCellEditor(new DefaultCellEditor(relationComboBox));
        TableColumn languageColumn = relationTable.getColumnModel().getColumn(2);
        JComboBox langComboBox = new JComboBox(wbService.getAllLanguages(dictionary).toArray());
        languageColumn.setCellEditor(new DefaultCellEditor(langComboBox));
        TableColumn wordColumn = relationTable.getColumnModel().getColumn(0);
        wordColumn.setCellRenderer(wordTextCellRenderer);
    }

    private boolean validateRelationTable() {
        clearValidation();
        DefaultTableModel model = (DefaultTableModel) relationTable.getModel();
        int count = 0;
        for (int row = 0; row < model.getRowCount(); row++) {
            String text = (String) model.getValueAt(row, 0);
            Relationship relationship = (Relationship) model.getValueAt(row, 1);
            Language language = (Language) model.getValueAt(row, 2);
            Word relatedWord = null;
            if (word != null && relationship != null && language != null) {
                relatedWord = wbService.getWord(dictionary, text, language);
            }
            if (relatedWord == null) {
                wordTextCellRenderer.addWrongRow(row);
                count++;
            } else {
                relationships.add(new WordRelationship(word, relatedWord, relationship));
            }
        }
        relationTable.repaint();
        if (count > 0) {
            resultLabel.setForeground(Color.RED);
            resultLabel.setText(Bundle.getMessage("AddWordDialog.validation.WRONG"));
        } else {
            resultLabel.setForeground(Color.BLACK);
            resultLabel.setText(Bundle.getMessage("AddWordDialog.validation.OK"));
        }
        return count == 0;
    }

    private void clearValidation() {
        wordTextCellRenderer.clear();
        relationships.clear();
        relationTable.repaint();
        resultLabel.setText("");
    }

    private void setWordReadOnly() {
        wordTextField.setEnabled(false);
        languageComboBox.setEnabled(false);
        typeComboBox.setEnabled(false);
    }

    public Word getWord() {
        return word;
    }

    public List<WordRelationship> getRelationships() {
        return relationships;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        wordLabel = new javax.swing.JLabel();
        wordTextField = new javax.swing.JTextField();
        languageComboBox = new javax.swing.JComboBox();
        languageLabel = new javax.swing.JLabel();
        typeLabel = new javax.swing.JLabel();
        typeComboBox = new javax.swing.JComboBox();
        addRelationButton = new javax.swing.JButton();
        removeRelationButton = new javax.swing.JButton();
        validateButton = new javax.swing.JButton();
        translationTableScrollPane = new javax.swing.JScrollPane();
        relationTable = new javax.swing.JTable();
        resultLabel = new javax.swing.JLabel();
        buttonPanel = new javax.swing.JPanel();
        saveButton = new javax.swing.JButton();
        cancelButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        wordLabel.setText(eu.easyedu.dictionary.gui.resources.Bundle.getMessage("AddWordDialog.wordLabel.text")); // NOI18N

        wordTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                wordTextFieldActionPerformed(evt);
            }
        });

        languageComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                languageComboBoxActionPerformed(evt);
            }
        });

        languageLabel.setText(eu.easyedu.dictionary.gui.resources.Bundle.getMessage("AddWordDialog.languageLabel.text")); // NOI18N

        typeLabel.setText(eu.easyedu.dictionary.gui.resources.Bundle.getMessage("AddWordDialog.typeLabel.text")); // NOI18N

        typeComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                typeComboBoxActionPerformed(evt);
            }
        });

        addRelationButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/eu/easyedu/dictionary/gui/resources/icons/list-add.png"))); // NOI18N
        addRelationButton.setToolTipText(Bundle.getMessage("AddWordDialog.addRelationButton.toolTipText")); // NOI18N
        addRelationButton.setPreferredSize(new java.awt.Dimension(18, 18));
        addRelationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addRelationButtonActionPerformed(evt);
            }
        });

        removeRelationButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/eu/easyedu/dictionary/gui/resources/icons/list-remove.png"))); // NOI18N
        removeRelationButton.setToolTipText(Bundle.getMessage("AddWordDialog.removeRelationButton.toolTipText")); // NOI18N
        removeRelationButton.setPreferredSize(new java.awt.Dimension(18, 18));
        removeRelationButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                removeRelationButtonActionPerformed(evt);
            }
        });

        validateButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/eu/easyedu/dictionary/gui/resources/icons/refresh.png"))); // NOI18N
        validateButton.setToolTipText(Bundle.getMessage("AddWordDialog.validateButton.toolTipText")); // NOI18N
        validateButton.setPreferredSize(new java.awt.Dimension(18, 18));
        validateButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                validateButtonActionPerformed(evt);
            }
        });

        relationTable.setModel(getRelationTableModel());
        translationTableScrollPane.setViewportView(relationTable);

        resultLabel.setFont(new java.awt.Font("Dialog", 1, 11)); // NOI18N
        resultLabel.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(204, 204, 204), 1, true));

        saveButton.setText(Bundle.getMessage("AddWordDialog.saveButton.text")); // NOI18N
        saveButton.setPreferredSize(new java.awt.Dimension(70, 24));
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(saveButton);

        cancelButton.setText(Bundle.getMessage("AddWordDialog.cancelButton.text")); // NOI18N
        cancelButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelButtonActionPerformed(evt);
            }
        });
        buttonPanel.add(cancelButton);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(buttonPanel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addComponent(translationTableScrollPane, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(wordLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                            .addComponent(languageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(typeLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(languageComboBox, 0, 253, Short.MAX_VALUE)
                            .addComponent(wordTextField, javax.swing.GroupLayout.DEFAULT_SIZE, 253, Short.MAX_VALUE)
                            .addComponent(typeComboBox, 0, 253, Short.MAX_VALUE)))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(addRelationButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(removeRelationButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(validateButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(resultLabel, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 376, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(wordLabel)
                    .addComponent(wordTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(languageLabel)
                    .addComponent(languageComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(typeLabel)
                    .addComponent(typeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addRelationButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(removeRelationButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(validateButton, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(translationTableScrollPane, javax.swing.GroupLayout.DEFAULT_SIZE, 108, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(resultLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    private void wordTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_wordTextFieldActionPerformed
        word.setWord(wordTextField.getText());
    }//GEN-LAST:event_wordTextFieldActionPerformed

    private void languageComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_languageComboBoxActionPerformed
        word.setLanguage((Language) languageComboBox.getSelectedItem());
    }//GEN-LAST:event_languageComboBoxActionPerformed

    private void typeComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_typeComboBoxActionPerformed
        word.setType((WordType) typeComboBox.getSelectedItem());
    }//GEN-LAST:event_typeComboBoxActionPerformed

    private void addRelationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addRelationButtonActionPerformed
        DefaultTableModel model = (DefaultTableModel) relationTable.getModel();
        model.addRow((Object[]) null);
    }//GEN-LAST:event_addRelationButtonActionPerformed

    private void removeRelationButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_removeRelationButtonActionPerformed
        int selectedRow = relationTable.getSelectedRow();
        if (selectedRow > -1) {
            ((DefaultTableModel) relationTable.getModel()).removeRow(selectedRow);
            clearValidation();
        }
    }//GEN-LAST:event_removeRelationButtonActionPerformed

    private void validateButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_validateButtonActionPerformed
        validateRelationTable();
    }//GEN-LAST:event_validateButtonActionPerformed

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        if (validateRelationTable()) {
            if (!wordExists) {
                word = wbService.addWord(dictionary, word, relationships);
                log.info("Word successfully inserted with ID: " + word.getId());
            } else {
                wbService.addRelationships(dictionary, relationships);
            }
            setVisible(false);
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    private void cancelButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelButtonActionPerformed
        setVisible(false);
    }//GEN-LAST:event_cancelButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addRelationButton;
    private javax.swing.JPanel buttonPanel;
    private javax.swing.JButton cancelButton;
    private javax.swing.JComboBox languageComboBox;
    private javax.swing.JLabel languageLabel;
    private javax.swing.JTable relationTable;
    private javax.swing.JButton removeRelationButton;
    private javax.swing.JLabel resultLabel;
    private javax.swing.JButton saveButton;
    private javax.swing.JScrollPane translationTableScrollPane;
    private javax.swing.JComboBox typeComboBox;
    private javax.swing.JLabel typeLabel;
    private javax.swing.JButton validateButton;
    private javax.swing.JLabel wordLabel;
    private javax.swing.JTextField wordTextField;
    // End of variables declaration//GEN-END:variables
}
